package org.example.task.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.example.task.converter.TaskConverterMapper;
import org.example.task.mapper.TaskMapper;
import org.example.task.model.dto.PageDTO;
import org.example.task.model.dto.task.CreateTaskDTO;
import org.example.task.model.po.LoginUser;
import org.example.task.model.po.Task;
import org.example.task.model.query.TaskPageQuery;
import org.example.task.model.vo.task.TaskPageVO;
import org.example.task.service.ITaskService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;


@Service
@RequiredArgsConstructor
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements ITaskService {
    private final TaskConverterMapper taskConverterMapper;
    @Override
    public boolean createTask(CreateTaskDTO createTaskDTO) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        Task task = taskConverterMapper.createTaskDTOToTask(createTaskDTO);
        task.setCreatorId(loginUser.getUser().getUserId());
        //TODO 要根据登陆的用户部门
        task.setDeptId(1L);
        task.setCreateTime(LocalDateTime.now());
        task.setUpdateTime(LocalDateTime.now());
        return save(task);
    }

    @Override
    public PageDTO<TaskPageVO> getTaskPage(TaskPageQuery taskPageQuery) {
        Page<Task> p= taskPageQuery.toPage();
        lambdaQuery().eq(taskPageQuery.getTitle()!=null,Task::getTitle,taskPageQuery.getTitle())
                .eq(taskPageQuery.getDeptId()!=null,Task::getDeptId,taskPageQuery)
                .eq(taskPageQuery.getStartTime()!=null,Task::getStartTime,taskPageQuery.getStartTime())
                .eq(taskPageQuery.getDueDate()!=null,Task::getDueDate,taskPageQuery.getDueDate())
                .eq(taskPageQuery.getPriority()!=null,Task::getPriority,taskPageQuery.getPriority())
                .eq(taskPageQuery.getStatus()!=null,Task::getStatus,taskPageQuery.getStatus())
                .page(p);
        return PageDTO.of(p, TaskPageVO.class);
    }
}
